package cn.org.zx.common.aop;

import java.util.*;

import org.aopalliance.intercept.MethodInvocation;

public class SQLFilter {
	
	public static void filte(MethodInvocation invocation){
		Object[] arguments = null;
		int argumentLen = 0;
		String argumentClass = null;
		String str = null;
		Map map = null;
		
		arguments = invocation.getArguments();
		argumentLen = arguments.length;
		for(int i=0;i<argumentLen;i++){
			
			if(arguments[i]==null) continue;
			
			argumentClass = arguments[i].getClass().getSimpleName();
			//System.out.println(argumentClass);
			if(argumentClass.equals("String")){
				str = (String) arguments[i];
				arguments[i] = filteStr(str);//替换sql关键字

			}else if(argumentClass.endsWith("Map")){
				map = (Map) arguments[i];
				arguments[i] = filteMap(map);
			}
		}
	}
	/**
	 * 过滤String中的sql关键字

	 * @param str
	 * @return
	 */
	private static String filteStr(String str){
		SQLKeyWord[] keywords = SQLKeyWord.values();
		int keywordNum = keywords.length;
		for(int i=0;i<keywordNum;i++){
			str = str.replaceAll("(?i)"+keywords[i],"");//不区分大小写的替换掉sql关键字

		}
		return str;
	}
	
	/**
	 * 过滤Map中的sql关键字

	 * @param map
	 * @return
	 */
	private static Map filteMap(Map map){
		Map mapReturn = new HashMap();
		Set keyset = map.keySet();
		Iterator keyiter = keyset.iterator();
		String strKey = null;
		Object objValue = null;
		String strValue = null;
		String[] strValues = null;
		String strClassType = null;
		while(keyiter.hasNext()){
			strKey = (String) keyiter.next();
			objValue = map.get(strKey);
			strValue = "";
			if(objValue!=null){
				strClassType = objValue.getClass().getSimpleName();
				if(strClassType.equals("String")){
					strValue = (String)objValue;
					objValue = filteStr(strValue);//替换sql关键字

				}else if(strClassType.equals("String[]")){
					strValues = (String[])objValue;
					for(int i=0;i<strValues.length;i++){
						strValue = strValues[i];
						strValues[i] = filteStr(strValue);
					}
					objValue = strValues;
				}
			}
			mapReturn.put(strKey, objValue);
		}
		return mapReturn;
	}
}
